package cn.w2.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

public class ModbusClient {
    private static final Logger LOG = LoggerFactory.getLogger(ModbusClient.class);
//    public static void main(String[] args) {
//
//        byte[] bytes = {
//                0x00, 0x03,
//                0x00, 0x00,
//                0x00, 0x06,
//                0x02,
//                0x03,
//                0x00, 0x05,
//                0x00, (byte) 0x02
//        };
//
//
//        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(12);
//        buf.writeBytes(bytes);
//
//        Bootstrap bootstrap = new Bootstrap()
//                .group(new NioEventLoopGroup())
//                .channel(NioSocketChannel.class)
//                .option(ChannelOption.SO_KEEPALIVE, true)
//                .handler(new ChannelInitializer<Channel>() {
//                    @Override
//                    protected void initChannel(Channel channel) throws Exception {
//                        channel.pipeline().addLast("h1",new ChannelInboundHandlerAdapter(){
//                            @Override
//                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                                log2((ByteBuf)msg);
//                                LOG.debug("{}",(ByteBuf)msg);
//                                Thread.sleep(1000);
//                                ctx.writeAndFlush(ctx.alloc().buffer().writeBytes(bytes));
//                            }
//                        })// 空闲检测
//                                .addLast(new IdleStateHandler(60, 0, 0))
//                                .addLast(new ReadTimeoutHandler(3 * 60));
//                    }
//                });
//
//        ChannelFuture connect = bootstrap.connect("127.0.0.1", 502);
//
//        connect.addListener(new ChannelFutureListener(){
//            @Override
//            public void operationComplete(ChannelFuture future) throws Exception {
//                future.channel().writeAndFlush(buf);
//            }
//        });
//    }


    private final String host;
    private final int port;


    public ModbusClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 502;
        new ModbusClient(host, port).start();
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            /// 指定 EventLoopGroup 以处理客户端事件；需要适用于 NIO 的实现
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, port))
                    //在创建Channel时，向 ChannelPipeline中添加一个 EchoClientHandler 实例
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(
                                    new ModbusClientHandler());
                        }
                    });
            ChannelFuture f = b.connect().sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}
